package com.leetcode;

import java.util.Deque;
import java.util.LinkedList;

/**
 * 388. 文件的最长绝对路径
 * 2022-04-20-每日一题
 * 栈
 *
 * @author fy
 * @date 2022/4/20 18:47
 */
public class Solution388 {

    public int lengthLongestPath(String input) {
        int idx = 0;
        Deque<String> stack = new LinkedList<>();

        int curLen = 0;
        int maxLen = -1;
        StringBuilder sb = new StringBuilder();
        while (idx <= input.length()) {
            if (idx < input.length() && (Character.isLetterOrDigit(input.charAt(idx)) || input.charAt(idx) == ' ' || input.charAt(idx) == '.')) {
                while (idx < input.length() && input.charAt(idx) != '\n') {
                    sb.append(input.charAt(idx++));
                }
            } else if (idx == input.length() || input.charAt(idx) == '\n') {
                curLen += sb.length() + 1;
                String str = sb.toString();
                if (str.contains(".")){
                    if (curLen > maxLen) {
                        maxLen = curLen;
                    }
                }
                stack.push(str);
                sb.setLength(0);
                idx++;

                int tCount = 1;
                while (idx < input.length() && input.charAt(idx) == '\t') {
                    tCount++;
                    idx++;
                }
                int size = stack.size();
                for (int i = 0; i < (size - tCount + 1); i++) {
                    String pStr = stack.pop();
                    curLen -= (pStr.length() + 1);
                }
            }
        }
        return maxLen == -1 ? 0 : maxLen - 1;
    }

    public static void main(String[] args) {
//        String input = "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext";
//        String input = "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext";
//        String input = "d";
//        String input = "file1.txt\nfile2.txt\nlongfile.txt";
        String input = "a\n\tb1\n\t\tf1.txt\n\taaaaa\n\t\tf2.txt";
/**
 * a
 *  b1
 *      f1
 *  aaaaa
 *      f2
 *
 *
 */
        int res = new Solution388().lengthLongestPath(input);
        System.out.println(res);
    }

}
